import React, { useEffect, useState } from 'react'
import { Button } from 'antd';
import DemoUseLayoutEffect from './Demo6UseLayoutEffect';
import "./Demo.less"

// 模拟从服务器异步获取数据
const queryData = () => {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve([10, 20, 30]);
    }, 1000);
  });
};

export default function Demo5useEffect() {
  let [num, setNum] = useState(0),
    [x, setX] = useState(100)


  useEffect(() => {
    console.log('@1', num);
  })
  useEffect(() => {
    console.log('@2', num);
  }, [])
  useEffect(() => {
    console.log('@3', x);
  }, [num]);
  useEffect(() => {
    return () => {
      // 获取的是上一次的状态值
      console.log('@4', num);
    };
  });

  // 第一次渲染完毕后，从服务器异步获取数据
  // useEffect(async () => {
  // 会报错
  //   let data = await queryData();
  //   console.log('成功：', data);
  // }, []);
  // useEffect(() => {
  //   queryData().then(data => {
  //     console.log('成功：', data);
  //   })
  // })
  useEffect(() => {
    const next = async () => {
      let data = await queryData()
      console.log('成功：', data);
    }
    next()
  })

  const handle = () => {
    setNum(num + 1);
  };

  return (
    <div>
      <div className="demo">
        <div>{num}</div>
        <Button type="primary"
          size="small"
          onClick={handle}>
          增加
        </Button>
      </div>
      <DemoUseLayoutEffect />
    </div>
  )
}
